package com.cszy.yydqbfq.service

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.widget.Toast

class AntiAddictionService : Service() {
    companion object {
        private const val TIME_LIMIT = 40 * 60 * 1000L // 40分钟，毫秒
    }

    private var startTime = 0L
    private var isRunning = false
    private lateinit var handler: Handler

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onCreate() {
        super.onCreate()
        handler = Handler(Looper.getMainLooper())
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        intent?.run {
            when {
                getBooleanExtra("start", false) -> {
                    startTime = System.currentTimeMillis()
                    isRunning = true
                    startTimer()
                }
                getBooleanExtra("stop", false) -> {
                    stopSelf()
                }
            }
        }
        return START_NOT_STICKY
    }

    private fun startTimer() {
        handler.postDelayed(object : Runnable {
            override fun run() {
                if (isRunning) {
                    val currentTime = System.currentTimeMillis()
                    val elapsedTime = currentTime - startTime

                    if (elapsedTime >= TIME_LIMIT) {
                        showTimeLimitDialog()
                        stopSelf()
                    } else {
                        handler.postDelayed(this, 1000) // 每秒检查一次
                    }
                }
            }
        }, 1000)
    }

    private fun showTimeLimitDialog() {
//        val dialogIntent = Intent(this, TimeLimitDialogActivity::class.java).apply {
//            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//        }
//        startActivity(dialogIntent)
        Toast.makeText(this,"到了时间了",Toast.LENGTH_LONG).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        isRunning = false
        handler.removeCallbacksAndMessages(null)
    }
}